package com.example.teaching_server.service;

import com.example.teaching_server.dto.LoginDTO;
import com.example.teaching_server.dto.LoginResultDTO;
import com.example.teaching_server.entity.UserEntity;
import com.example.teaching_server.repository.UserRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;
import java.util.UUID;

/**
 * 认证授权服务
 */
@Slf4j
@Service
@RequiredArgsConstructor
@Transactional(readOnly = true)
public class AuthService {

    private final UserRepository userRepository;

    /**
     * 用户登录
     */
    @Transactional
    public LoginResultDTO login(LoginDTO loginDTO) {
        log.info("用户登录尝试: {}", loginDTO.getUsername());

        LoginResultDTO result = new LoginResultDTO();
        Optional<UserEntity> userOpt = userRepository.findByUsername(loginDTO.getUsername());

        if (userOpt.isEmpty()) {
            log.warn("登录失败: 用户不存在 - {}", loginDTO.getUsername());
            result.setSuccess(false);
            result.setMessage("用户不存在");
            return result;
        }

        UserEntity user = userOpt.get();

        if (!user.getPassword().equals(loginDTO.getPassword())) {
            log.warn("登录失败: 密码错误 - {}", loginDTO.getUsername());
            result.setSuccess(false);
            result.setMessage("密码错误");
            return result;
        }

        String token = "demo-token-" + user.getId() + "-" + UUID.randomUUID();

        result.setSuccess(true);
        result.setMessage("登录成功");
        result.setToken(token);
        result.setUser(user);

        log.info("登录成功: {}", loginDTO.getUsername());
        return result;
    }
}
